package com.hrm.company.controller;

import com.hrm.common.controller.BaseController;
import com.hrm.common.entity.Result;
import com.hrm.common.entity.ResultCode;
import com.hrm.company.service.CompanyService;
import com.hrm.company.service.DepartmentService;
import com.hrm.domain.company.Company;
import com.hrm.domain.company.Department;
import com.hrm.domain.company.response.DeptListResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping(value = "/company/department")
@Api(value = "/company/department", tags = "<code>部门相关的接口</code>")
public class DepartmentController extends BaseController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CompanyService companyService;

    /**
     * 保存
     * @return
     */
    @ApiOperation("保存部门")
    @PostMapping("")
    public Result save(@RequestBody @ApiParam("部门对象") Department department) {
        /**
         * 1. 设置保存的企业id
         * 2. 调用service保存企业
         * 3. 返回结果
         */
        department.setCompanyId(companyId);
        departmentService.save(department);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 查询企业的部门列表
     * 指定企业id
     * @return
     */
    @ApiOperation("查询企业部门列表")
    @GetMapping("")
    public Result findAll() {
        Company company = companyService.findById(companyId);
        List<Department> list = departmentService.findAll(companyId);
        DeptListResult deptListResult = new DeptListResult(company, list);
        return new Result(ResultCode.SUCCESS, deptListResult);
    }

    /**
     * 根据id查询部门
     */
    @ApiOperation("根据id查询部门")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") @ApiParam("部门id") String id) {
        Department department = departmentService.findById(id);
        return new Result(ResultCode.SUCCESS, department);
    }

    /**
     * 根据id更新部门
     * @param id
     * @param department
     * @return
     */
    @ApiOperation("修改部门")
    @PutMapping("/{id}")
    public Result update(@PathVariable @ApiParam("部门id") String id,
                         @RequestBody @ApiParam("部门对象") Department department) {
        department.setId(id);
        Department department1 = departmentService.findById(id);
        department.setParentId(department1.getParentId());
        departmentService.update(department);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id删除部门
     * @param id
     * @return
     */
    @ApiOperation("删除部门")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable @ApiParam("部门id") String id) {
        departmentService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }
}
